from flask import Flask,request,json,jsonify #导入flask
app=Flask(__name__) #实例化flask

from config import Config
app.config.from_object(Config)

from db import db1

from flask_cors import CORS
CORS(app)


# 分类接口
@app.route('/cateM',methods=['POST'])
def cateM():
    if request.method =='POST':
        #获取前端传递的数据
        data=request.data
        if data:
            data=json.loads(data)
        else:
            data=request.form
    #添加到数据库
    sqL="insert into cate values(0,'%s')"%(data['name'])
    db1.insert(sqL)
    #返回
    return jsonify({'code':200})

# 分类展示接口
@app.route('/cate')
def cate():
    #获取所有分类
    sql="select * from cate"
    res=db1.findall(sql)
    #返回
    return jsonify({'code':200,'list':res})
    
#商品添加接口
@app.route('/goodsM',methods=['POST'])
def goodsM():
    if request.method =='POST':
        #获取前端传递的数据
        data=request.data
        if data:
            data=json.loads(data)
        else:
            data=request.form
    #添加到数据库
    sql="insert into goods values('%s','%s',0)"%((data['cate'],data['name']))
    db1.insert(sql)
    #返回
    return jsonify({'code':200})

# 商品展示接口
@app.route('/good',methods=['GET'])
def good():
    # 获取cate
    uid=int(request.args.get('uid'))
    if uid>0:
        #通过id获取商品信息
        cate=request.args.get('cate')
        sql="select * from goods where cate='%s' order by id desc"%(cate)
    #获取所有分类
    else:
        sql="select * from goods order by id desc"
    res=db1.findall(sql)
    #返回
    return jsonify({'code':200,'list':res})
    
        
        



if __name__ == '__main__':
    app.run()
    
